package com.metadata_system.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import com.metadata_system.common.db.mapper.UploadFileMapper;
import com.metadata_system.common.dto.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * 文件上传
 *
 * @author YangXiuTeng
 * @date Jun 1, 2015
 */
@Component
@Slf4j
public class UploadFileUtil {

    @Value("${metadata-system.upload-path:/www/wwwroot/upload-file.metadata-system.cc/}")
    private String myUploadPath = "upload-file/";

    // 上传文件-访问域名,默认(http://tsca-upload-file.cc/)
    @Value("${metadata-system.upload-url:http://upload-file.metadata-system.cc}")
    private String uianUploadDoname;

    // 图片最大 20M
    public static long maxImageSize = 1024 * 20;

    // 视频最大 300M
    public static long maxVideoSize = 1024 * 300;

    @Autowired(required = false)
    UploadFileMapper uploadFileMapper;


    public static String getFileSuffix(MultipartFile multipartFile) {
        HashMap<String, String> suffixNameMap = new HashMap<>();
        suffixNameMap.put("image/jpeg", ".jpg");
        suffixNameMap.put("image/png", ".png");
        suffixNameMap.put("image/gif", ".gif");
        suffixNameMap.put("video/quicktime", ".mov");
        suffixNameMap.put("video/mp4", ".mp4");
        suffixNameMap.put("application/pdf", ".pdf");
        suffixNameMap.put("application/vnd.ms-excel", ".xls");
        suffixNameMap.put("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx");

        System.out.println("multipartFile.getContentType(): "+multipartFile.getContentType());

        String type = suffixNameMap.get(multipartFile.getContentType());
        if (type == null) {
            if (Objects.requireNonNull(multipartFile.getContentType()).contains("image")) {
                throw new RuntimeException("只允许上传 jpg,jpeg,png,gif 格式图片");
            }
            if (multipartFile.getContentType().contains("video")) {
                throw new RuntimeException("只允许上传 mov,mp4 格式视频");
            }
        }
        long size = multipartFile.getSize() / (1024);
        if (Objects.requireNonNull(multipartFile.getContentType()).contains("image")) {
            if (size > maxImageSize) {
                throw new RuntimeException("上传【图片】大小不能超过 20M");
            }
        }
        if (multipartFile.getContentType().contains("video")) {
            if (size > maxVideoSize) {
                throw new RuntimeException("上传【视频】大小不能超过 300M");
            }
        }
//        log.info("size: " + size);
        return type;
    }

    /**
     * 上传文件
     *
     * @param multipartFile 文件对象
     * @return
     */
    public String uploadFileBackPath(MultipartFile multipartFile) throws IOException {
        if (multipartFile.isEmpty()) {
            throw new RuntimeException("请选择文件");
        }
        // 文件后缀 例如：.png
        String fileSuffix = getFileSuffix(multipartFile);
        // uuid 生成文件名
        String uuid = DateTimeUtil.formatDateTimetoString(new Date(), "HHmmssS");
        // 根路径，在 /file/upload-file/2021-10-03/
        String dir = DateTimeUtil.formatDateTimetoString(new Date(), DateTimeUtil.FMT_yyyyMMdd) + "/";

        String basePath = myUploadPath + "/" + dir;
        // 新的文件名，使用uuid生成文件名
        String fileName = Base62Encoder.encode(Long.parseLong(uuid)) + fileSuffix;
        // 创建新的文件
        File fileExist = new File(basePath);
        // 文件夹不存在，则新建
        if (!fileExist.isDirectory()) {
            Files.createDirectories(Paths.get(basePath));
        }
        // 获取文件对象
        File file = new File(basePath, fileName);

        // 完成文件的上传
        multipartFile.transferTo(file);
        // 访问路径
        String path = dir + fileName;


        // mov文件转mp4
//        String fileAbsolutePath = fileExist.getAbsolutePath() + "/" + fileName;
//        if (fileSuffix.equals(".mov")) {
//            String newAbsolutePath = (fileAbsolutePath).replace("mov", "mp4");
////            MyUtil.MovToMp4(fileAbsolutePath,newAbsolutePath);
//            Files.delete(Paths.get(fileAbsolutePath));
//            return path.replace("mov", "mp4");
//        }
//            log.info("上传后路径: "+path);
        return "/"+path;
    }


    /**
     * 上传文件返回path
     *
     * @param multipartFile
     * @return
     */
    public ApiResult uploadFile(MultipartFile multipartFile) {
        String path;
        try {
            path = this.uploadFileBackPath(multipartFile);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error(e.getMessage());
        }
        return ApiResult.success(path);
    }
}

